// 顶点着色器
var VSHADER_SOURCE = 
  'attribute vec4 a_Position;\n' + // 将从js读取值 
  'void main() {\n' +
  '  gl_Position = a_Position;\n' + // 设置坐标
  '  gl_PointSize = 10.0;\n' +                    // 设置尺寸
  '}\n';

// 片元着色器程序
var FSHADER_SOURCE =
	'precision mediump float;\n' +
	'uniform vec4 u_FragColor;\n' +
	'void main() {\n' +
	'  gl_FragColor = u_FragColor;\n' + // 设置颜色
	'}\n';

function main() {
	var canvas = document.getElementById('webgl');
	var gl = getWebGLContext(canvas);
	if (!gl) {
		console.log('Failed to get the rendering context for WebGL');
		return;
	}
	// 初始化着色器
	if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
		console.log('Failed to intialize shaders.');
		return;
	}
  
	// 获取attribute变量的存储位置
	var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
	if(a_Position < 0) {
		console.log('Failed to get the storage location of a_Position');
		return;
	}
	
	// 获取u_FragColor变量的存储位置
	var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
	
	// 注册鼠标点击响应函数
	canvas.onmousedown = function(ev){
		click(ev, gl, canvas, a_Position, u_FragColor);
	}
	  
	gl.clearColor(0.0, 0.0, 0.0, 1.0);
	gl.clear(gl.COLOR_BUFFER_BIT);
}

var gPoints = []; // 鼠标点击位置数组
var gColors = [];
function click(ev, gl, canvas, a_Position, u_FragColor){
	var x = ev.clientX; // 鼠标点击的x坐标
	var y = ev.clientY; // 鼠标点击处的y坐标
	var rect = ev.target.getBoundingClientRect();
	x = ((x - rect.left) - canvas.width/2)/(canvas.width/2);
	y = (canvas.height/2 - (y - rect.top)) / (canvas.height/2);
	gPoints.push({x:x,y:y});
	gColors.push({r:Math.random().toFixed(1),g:Math.random().toFixed(1),b:Math.random().toFixed(1),a:1.0})
	// 先清除再绘制
	gl.clear(gl.COLOR_BUFFER_BIT);
	for(var i= 0; i < gPoints.length; i++){
		// 将顶点位置传输给attribute变量
		gl.vertexAttrib3f(a_Position, gPoints[i].x, gPoints[i].y, 0.0);
		// 将点的颜色传输到u_FragColor变量中
		gl.uniform4f(u_FragColor, gColors[i].r, gColors[i].g, gColors[i].b, gColors[i].a);
		// 绘制一个点
		// gl.POINTS 点
		// 常用 gl.LINES gl.LINE_STAIP gl.LINE_LOOP gl.TRIANGLES gl.TRIANGLE_STRIP gl.TRIANGLE_FAN
		gl.drawArrays(gl.POINTS, 0, 1);
	}
}
